﻿using System;
using System.Runtime.InteropServices;

namespace BitmapPtr
{

    internal class SharedPinnedByteArray
    {
        internal byte[] bits;
        internal GCHandle handle;
        internal IntPtr bitPtr;

        int refCount;

        public SharedPinnedByteArray(int length)
        {
            bits = new byte[length];
            // if not pinned the GC can move around the array
            handle = GCHandle.Alloc(bits, GCHandleType.Pinned);
            bitPtr = Marshal.UnsafeAddrOfPinnedArrayElement(bits, 0);
            refCount++;
        }

        internal void AddReference()
        {
            refCount++;
        }

        internal void ReleaseReference()
        {
            refCount--;
            if (refCount <= 0)
                Destroy();
        }

        bool destroyed;
        private void Destroy()
        {
            if (!destroyed)
            {
                handle.Free();
                bits = null;
                destroyed = true;
            }
        }

        ~SharedPinnedByteArray()
        {
            Destroy();
        }
    }
}
